package io.jee.runshan.utils;

import io.jee.medusa.remote.RemoteConnector;
import io.jee.runshan.domain.remote.qiye.AccessToken;

import java.util.Date;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class QiyeConstant {
	private static final String WeishequPropertiesFile = "qiye.properties";
	private static Logger logger = LoggerFactory.getLogger(QiyeConstant.class);

	/**
	 * 最新的Token
	 */
	private static String AccessToken;
	/**
	 * 最后一次获取Token的时间（毫秒）
	 */
	private static long AccessTokenGeted = 0L;
	/**
	 * 最后一次Token的有效时间（毫秒）
	 */
	private static long AccessTokenExpiresIn = 0L;

	private static Map<String, String> property = null;

	/**
	 * 获取Token
	 * @Created: 2015年2月6日
	 * @Last_modified: 2015年2月6日 下午7:11:18
	 * @Last_modified_by: ynshun
	 * @Create_by: ynshun
	 * 
	 * @return
	 */
	public static String getApptoken() {
		long currentTime = new Date().getTime();
		if (currentTime - AccessTokenExpiresIn > AccessTokenGeted) {
			String CorpID = getProperty("CorpID");
			String Secret = getProperty("Secret");
			String url = getProperty("appTokenUrl") + "?corpid=" + CorpID + "&corpsecret=" + Secret;
			AccessToken token = RemoteConnector.get(url, null, AccessToken.class);
			AccessToken = token.getAccess_token();
			AccessTokenGeted = currentTime;
			AccessTokenExpiresIn = token.getExpires_in();
		}
		return AccessToken;
	}
	
	public static Integer getAgentid() {
		return Integer.parseInt(getProperty("assistantAgentid"));
	}
	
	public static String getProperty(String key) {
		if (property == null) {
			property = PropertiesUtils.toMap(PropertiesUtils.loadProperties(WeishequPropertiesFile));
			logger.debug("load Qiye Properties File Success!!!");
		}
		return property.get(key);
	}

	public static String getProperty(int key) {
		if (property == null) {
			property = PropertiesUtils.toMap(PropertiesUtils.loadProperties(WeishequPropertiesFile));
			logger.debug("load Qiye Properties File Success!!!");
		}
		return getProperty(String.valueOf(key));
	}
}
